<template>
  <el-form  ref="fruitRules" :model="fruit" :rules="rules" label-width="80px" class="fruitFromClass" style="width: 600px">
    <el-form-item label="名称" prop="name">
      <el-input v-model="fruit.name"></el-input>
    </el-form-item>
    <el-form-item label="销量" prop="sale">
      <el-input v-model.number="fruit.sale"></el-input>
    </el-form-item>
    <el-form-item label="图片" prop="icon">
      <el-input v-model="fruit.icon"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit('fruitRules')">立即创建</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'AddFruit',
  data () {
    return {
      fruit: {
        name: '',
        sale: '',
        icon: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入水果名称', trigger: 'blur' }
        ],
        sale: [
          { required: true, message: '请输入销量', trigger: 'blur' },
          { type: 'number', message: '销量必须为数字值' }
        ],
        icon: [
          { required: true, message: '请输入图片链接', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onSubmit (fruitform) {
      this.$refs[fruitform].validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.axios.post('/fruit/add', this.fruit)
          console.log('addFruitResp:', res)
          if (res) {
            this.$alert(this.fruit.name + '添加成功！', '添加数据', {
              confirmButtonText: '确定',
              callback: action => {
                this.$message.success('增加成功')
                this.$router.push('/fruitlist')
              }
            })
          } else {
            this.$message.error('增加失败！！！')
          }
        }
      })
    },
    cancel () {
      this.$router.push('/fruitlist')
    }
  }
}
</script>

<style  scoped>
.fruitFromClass{
  text-align: center;
  margin: 0 auto;
}
</style>
